package cloud.agileframework.common.util.ip;

import cloud.agileframework.common.util.clazz.TypeReference;
import cloud.agileframework.common.util.object.ObjectUtil;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.writer.ObjectWriter;
import org.apache.commons.lang3.math.NumberUtils;

import java.lang.reflect.Type;

public class IPWriter implements ObjectWriter<Long> {
    @Override
    public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
        if (object == null) {
            return;
        }
        String ip;
        Long ipLong;
        if (object instanceof Number) {
            ipLong = ObjectUtil.to(((Number) object).longValue(), new TypeReference<>(fieldType));
        } else {
            if (NumberUtils.isCreatable(object.toString())) {
                ipLong = ObjectUtil.to(object, new TypeReference<>(Long.class));
            } else {
                jsonWriter.writeAny(object);
                return;
            }
        }
        ip = IPv4Util.longToIP(ipLong);
        jsonWriter.writeString(ip);
    }
}
